package com.herench.bs.support;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Created by ThinkPad on 2017/8/24.
 */
public class SimpleServicePool implements CleverContextAware, ServicePool<String, MessageHandler> {


    protected final ConcurrentMap<String, MessageHandler> pool = new ConcurrentHashMap<>();
    protected CleverClinicContext cleverClinicContext;

    @Override
    public CleverClinicContext getCleverClinicContext() {
        return cleverClinicContext;
    }

    @Override
    public void setCleverClinicContext(CleverClinicContext cleverClinicContext) {
        this.cleverClinicContext = cleverClinicContext;
    }


    @Override
    public MessageHandler addAndAcquire(String functionCode, MessageHandler messageHandler) {
        MessageHandler handler = pool.get(functionCode);
        if (handler != null) {
            throw new RuntimeException(functionCode + " messageHandler已经存在.");
        }
        pool.put(functionCode, messageHandler);
        return messageHandler;
    }

    @Override
    public MessageHandler acquire(String functionCode) {
        MessageHandler answer = pool.get(functionCode);
        return answer;
    }

    @Override
    public void release(String functionCode, MessageHandler messageHandler) {
        pool.put(functionCode, messageHandler);
    }

    @Override
    public boolean remove(String functionCode) {
        MessageHandler remove = pool.remove(functionCode);
        return remove != null;
    }

    @Override
    public boolean isExist(String functionCode) {
        return pool.containsKey(functionCode);
    }

    @Override
    public int size() {
        return this.pool.size();
    }

    @Override
    public void purge() {
        this.pool.clear();
    }

    @Override
    public List<MessageHandler> getServices() {
        List<MessageHandler> services = new ArrayList<>();
        for (Map.Entry<String, MessageHandler> entry : this.pool.entrySet()) {
            services.add(entry.getValue());
        }
        return services;
    }
}
